﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.CloudSaver.Web.Infrastructure;

namespace Microsoft.CloudSaver.Web.Admin
{
    public partial class EditUser : LocalizedPage
    {
        public string UserID { get; set; }
        public MembershipUser CurrentUser { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //Checks if it is a user deletion o editing request
                CurrentUser = Membership.GetUser(UserID = Request["UserID"]);
                if (!IsPostBack)
                {
                    string action = Request["Action"];
                    if (action != null && action == "delete" && CurrentUser.UserName!=Page.User.Identity.Name)
                    {
                        Membership.DeleteUser(CurrentUser.UserName);
                        Response.Redirect("~/Admin/Admin.aspx");
                    }
                    else
                    {
                        if (CurrentUser.UserName == Page.User.Identity.Name)
                        {
                            optRoles.Enabled = chkEnabled.Enabled= false;
                        }
                        lblHead.Text = string.Format(lblHead.Text, CurrentUser.UserName);
                        txtEmail.Text = CurrentUser.Email;
                        chkEnabled.Checked = CurrentUser.IsApproved;
                        optRoles.SelectedIndex = Roles.IsUserInRole(CurrentUser.UserName, "Admin") ? 0 : 1;
                    }
                }
            }
            catch (Exception)
            {
                Response.Redirect("~/Admin/Admin.aspx");
            }
        }

        protected void cmdDone_Click(object sender, ImageClickEventArgs e)
        {
            //Performs security checks on current logged user
            if (txtEmail.Text != CurrentUser.Email) CurrentUser.Email = txtEmail.Text;
            
            if (!string.IsNullOrEmpty(txtPassword.Text))
            {
                var tmp = CurrentUser.ResetPassword();
                CurrentUser.ChangePassword(tmp, txtPassword.Text);
            }
            if (CurrentUser.UserName!=Page.User.Identity.Name && !Roles.IsUserInRole(CurrentUser.UserName, optRoles.SelectedValue))
            {
                if (chkEnabled.Checked != CurrentUser.IsApproved) CurrentUser.IsApproved = chkEnabled.Checked;
                Roles.RemoveUserFromRoles(CurrentUser.UserName, new string[] { "Admin", "User" });
                Roles.AddUserToRole(CurrentUser.UserName, optRoles.SelectedValue);
            }
            Membership.UpdateUser(CurrentUser);
            Response.Redirect("~/Admin/Admin.aspx");
        }
    }
}